<template>
    <!-- 上门自提 -->
    <div class="delivery-door">
        <div class="delivery-door-header">
            <span class="name">上门自提</span
            ><el-popconfirm
                icon="WarningFilled"
                placement="top"
                width="200px"
                :title="switchTitle"
                :disabled="isDisabled"
                @confirm="confirmSwitch">
                <template #reference
                    ><el-switch
                        :disabled="isDisabled"
                        class="custom-switch"
                        v-model="switchForm.switchOn"
                        :inline-prompt="true"
                        :active-value="1"
                        :inactive-value="2"
                        active-text="开"
                        inactive-text="关"
                        :before-change="handleBeforeChange" /></template
            ></el-popconfirm>
            <div class="tip">启用后，买家下单可以选择上门自提。</div>
        </div>
        <div class="delivery-door_bottom">
            <!-- 新增操作 -->
            <div class="delivery-door-add">
                <el-button type="primary" @click="routerHandler(type)" v-auth="'delivery_management:self_site'"
                    >新增自提点</el-button
                >
            </div>
            <!-- 列表 -->
            <el-table :data="tableList" :stripe="true">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template v-if="['contactMobile', 'operations'].includes(prop)" #default="{ row }">
                        <template v-if="prop == 'contactMobile'">
                            {{ row.contactName }}（{{ row.contactMobile }}）
                        </template>
                        <template v-if="prop === 'operations'">
                            <el-button
                                v-for="{ label, fn, ref, auth } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                v-auth="auth"
                                :ref="el => setItemRef(el, `${ref}${row.id}`)"
                                class="table-button"
                                >{{ label }}</el-button
                            >
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-popovers-class not-close"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :effect="popoverText ? 'dark' : 'light'"
            :width="currentRow.ref === 'spreadButtonRef' ? 216 : 240"
            :visible="popoverVisible">
            <!-- todo:不同的内容 -->
            <!-- todo:不同的内容 -->
            <div
                class="custom-popovers-class-main"
                v-click-outside="onClickOutside"
                v-if="['enabledButtonRef', 'disabledButtonRef', 'removeButtonRef'].includes(currentRow.ref)">
                <!-- 启用 -->
                <h3 style="margin-bottom: 16px" v-if="currentRow.ref == 'enabledButtonRef'">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>确定要启用该自提点吗？
                </h3>
                <!-- 停用 -->
                <template v-if="currentRow.ref == 'disabledButtonRef'">
                    <h3 style="margin-bottom: 16px">
                        <el-icon class="custom-icon"><WarningFilled /></el-icon>确定要停用该自提点吗？
                    </h3>
                    <template v-if="popoverText">
                        {{ popoverText }}
                    </template>
                </template>
                <!-- 删除 -->
                <template v-if="currentRow.ref == 'removeButtonRef' && popoverVisible">
                    <h3 style="margin-bottom: 16px" v-if="!popoverText">
                        <el-icon class="custom-icon"><WarningFilled /></el-icon>确定要删除该自提点吗？
                    </h3>
                    <template v-if="popoverText">
                        {{ popoverText }}
                    </template>
                </template>
                <div style="text-align: right" v-if="!popoverText && popoverVisible">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
            <div class="custom-popovers-class-main" v-click-outside="onClickOutside" v-else>
                {{ popoverText }}
            </div>
        </el-popover>
    </div>
</template>

<script setup name="deliveryDoor">
import store from '@/store/index';
import { ElMessage } from 'element-plus';
import request from '@/request/index';
import { ref, reactive, computed, onMounted, onUnmounted, onActivated, onDeactivated, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ClickOutside as vClickOutside } from 'element-plus';
import Pagination from '@/components/Pagination.vue';
import { cloneDeep } from '@/commons/utils';

const router = useRouter();

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
const isDisabled = computed(() => {
    return !permissions.has('delivery_management:edit_way');
});

const switchForm = reactive({
    id: null,
    switchOn: 2 // todo:false
});

const switchTitle = computed(() => {
    return switchForm.switchOn == 1
        ? '关闭上门自提后，客户将无法选择上门自提。确定要关闭上们自提吗？'
        : '开启上门自提后，客户将可以选择上门自提。确定要开启上门自提吗？';
});

const handleBeforeChange = async () => {};

const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10 //默认每页15条
});
let formClone = reactive(null);
const totalCount = ref(0);
let tableList = reactive([]);
let isEdit = ref(false);

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null, id: null, status: null });

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '自提点名称', prop: 'selfLiftName', showOverflowTooltip: true, minWidth: '150' },
        { label: '自提点地址', prop: 'activityTypeText', showOverflowTooltip: true, minWidth: '250' },
        { label: '联系人', prop: 'contactMobile', width: '200', showOverflowTooltip: true },
        { label: '营业时间', prop: 'siteExtensionText', minWidth: '200', showOverflowTooltip: true },
        { label: '状态', prop: 'enableText', width: '80' },
        { label: '操作', prop: 'operations', width: '200', fixed: 'right' }
    ];
    return baseTableColumns;
});
let popoverText = ref();

const nameRouteHandler = ({ id }, type) => {
    const useAuth = store.useAuthStore();
    const permissions = useAuth.permissions;
    const code = 'freight_list:view';
    if (!permissions.has(code)) {
        ElMessage({
            type: 'error',
            message: '当前用户没有查看权限'
        });
        return false;
    }
    const { href } = router.resolve({
        path: '/marketing/freight/detail',
        query: {
            id,
            type
        }
    });
    window.open(href, '_blank');
};
const routerHandler = type => {
    // 跳转新增运费模板
    isEdit.value = true;
    router.push({ path: '/order/delivery/doorAdd' });
};
// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const res = await request('selfLiftLists', form);
    const list = (res.data.list || []).map(item => {
        item.enableText = item.enable == 1 ? '已启用' : '已停用';
        item.activityTypeText = `${item.provinceIdName || ''}${item.cityIdName || ''}${item.areaIdName || ''}${
            item.street || ''
        }`;
        const weeks = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        const hasWeek = item.siteExtension.map(item => weeks[item.weekTime - 1]);
        item.siteExtensionText = weeks
            .reduce(
                (prev, curr, currentIndex) => {
                    if (currentIndex == prev.total && hasWeek.find(item => item == curr)) {
                        prev.weeks[prev.arrI] = prev.weeks[prev.arrI] || [];
                        prev.weeks[prev.arrI].push(curr);
                    } else {
                        prev.arrI = prev.weeks.length;
                    }
                    prev.total = prev.total + 1;
                    return prev;
                },
                {
                    total: 0,
                    arrI: 0,
                    weeks: []
                }
            )
            ?.weeks?.map(item => {
                if (item.length > 2) {
                    return `${item[0]}至${item[item.length - 1]}`;
                }
                return item.join('、');
            })
            ?.join('、');
        const { timeSegmentStart, timeSegmentEnd } = item?.siteExtension?.[0] || {};
        item.siteExtensionText = item.siteExtensionText + ' ' + timeSegmentStart + '-' + timeSegmentEnd;
        // todo: 根据不同状态显示不同按钮
        // todo:权限,停用状态是否能返回已被使用的状态
        const btns = [
            { label: '编辑', fn: editHandler, ref: 'editButtonRef', auth: 'delivery_management:self_site' },
            { label: '停用', fn: disabledHandler, ref: 'disabledButtonRef', auth: 'delivery_management:self_site' },
            { label: '启用', fn: enabledHandler, ref: 'enabledButtonRef', auth: 'delivery_management:self_site' },
            { label: '删除', fn: removeHandler, ref: 'removeButtonRef', auth: 'delivery_management:self_site' }
        ];
        if (item.enable == 1) {
            item.operations = [btns[0], btns[1]];
        } else if (item.enable == 2) {
            item.operations = [btns[0], btns[2], btns[3]];
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryCouponListHandler();
};
/** 按钮组操作 */
const popoverHandler = ({ id, enable }, ref) => {
    buttonRef.value = itemRefs[`${ref}${id}`];
    currentRow.ref = ref;
    currentRow.id = id;
    currentRow.enable = enable;

    nextTick(() => {
        popoverVisible.value = true;
    });
};
// 编辑
const editHandler = row => {
    isEdit.value = true;
    router.push({
        path: '/order/delivery/doorEdit',
        query: {
            id: row.id
        }
    });
};
// 启用
const enabledHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 停用
const disabledHandler = async (row, ref) => {
    popoverHandler(row, ref);
};
// 删除
const removeHandler = async (row, ref) => {
    // todo:验证是否能删除
    const { msg } = await request('selfLiftNotify', { id: row.id });
    if (msg) {
        popoverText.value = msg;
    }
    popoverHandler(row, ref);
};
// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    if (!visible) {
        popoverText.value = null;
    }
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    const apiName = {
        disabledButtonRef: 'selfLiftEnable',
        removeButtonRef: 'selfLiftDel',
        enabledButtonRef: 'selfLiftEnable'
    };
    const params = {
        id: currentRow.id
    };
    if (['disabledButtonRef', 'enabledButtonRef'].includes(currentRow.ref)) {
        params.enable = currentRow.enable == 1 ? 2 : 1;
    }
    await request(apiName[currentRow.ref], params);
    popoverVisibleHandler();
    queryCouponListHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
};

const getConfig = async () => {
    const { data = {} } = await request('refundAddressInfo');
    switchForm.switchOn = data?.shopSelfLiftSwitch;
    switchForm.id = data?.id;
};

const confirmSwitch = async () => {
    await request('refundAddressSave', {
        shopSelfLiftSwitch: switchForm.switchOn == 2 ? 1 : 2,
        saveType: 'self_lift_switch',
        id: switchForm.id
    });
    switchForm.switchOn = switchForm.switchOn == 2 ? 1 : 2;
};

const getAllData = () => {
    getConfig();
    searchHandler();
};

onMounted(() => {
    if (isEdit.value) {
        queryCouponListHandler();
        isEdit.value = false;
    } else {
        form.pageSize = 10;
        getAllData();
    }
    // setLayout();
});
onUnmounted(() => {
    // resetLayout();
});

onActivated(() => {
    if (isEdit.value) {
        queryCouponListHandler();
        isEdit.value = false;
    } else {
        form.pageSize = 10;
        getAllData();
    }
    // setLayout();
});
onDeactivated(() => {
    // resetLayout();
});
</script>
<style lang="scss">
.custom-popovers-class {
    padding: 16px;
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 0 0 16px;
    }

    p + div {
        text-align: right;
    }

    .custom-preview {
        margin-top: 16px;
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
    }

    &-main {
        padding: 16px;
    }
}
</style>
<style lang="scss" scoped>
@import './index.scss';
</style>
